package com.atkxp.controller;

import com.atkxp.pojo.Blog;
import com.atkxp.pojo.MyPair;
import com.atkxp.pojo.Page;
import com.atkxp.pojo.User;
import com.atkxp.service.BlogService;
import com.atkxp.service.CommentService;
import com.atkxp.service.UserService;
import org.ocpsoft.prettytime.PrettyTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.*;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author user
 * @declaration
 * @create 2022/11/1-20:26
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private CommentService commentService;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String name, String password, HttpServletRequest req){
        User login = userService.login(name, password);
        if(login != null){
            req.getSession().setAttribute("user", login);
            return "login_success";
        }else{
            req.setAttribute("msg", "密码错误或用户名不存在");
            req.setAttribute("username", name);
            return "login";
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        req.getSession().invalidate();
        return "redirect:/";
    }

    @RequestMapping("/toRegist")
    public String toRegist(){
        return "regist";
    }

    @RequestMapping("/registUser")
    public String regist(User user, HttpServletRequest req, String code){
        String token = (String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if(token != null && token.equalsIgnoreCase(code)){
            if(userService.existUserName(user.getName())){
                req.setAttribute("msg", "用户名已存在!");
                req.setAttribute("username", user.getName());
                req.setAttribute("email", user.getEmail());
                return "regist";
            }else{
                userService.registUser(user);
                return "regist_success";
            }
        }else{
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", user.getName());
            req.setAttribute("password", user.getPassword());
            req.setAttribute("email", user.getEmail());
            return "regist";
        }
    }

    @RequestMapping("/toUpdateUserInfo")
    public String toUpdateUserInfo(){
        return "updateInfo";
    }

    @RequestMapping("/updateUserInfo")
    public String updateUserInfo(User user, HttpServletRequest req, String code){
        String token = (String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if(token != null && token.equalsIgnoreCase(code)){
            userService.updateUser(user);
            req.getSession().setAttribute("user", user);
            req.setAttribute("msg", "修改成功");

        }else{
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", user.getName());
            req.setAttribute("password", user.getPassword());
            req.setAttribute("email", user.getEmail());
        }
        return "updateInfo";
    }
    @RequestMapping(value = "/uploadImg")
    @ResponseBody
    public String uploadImg(@RequestParam(value = "file",required = false) MultipartFile img,
                         String name) throws IOException, SQLException {

        if(img!=null){
            if(Math.floor((double)img.getSize()/1024)>16 * 1024){
                return "error"+ "文件太大！";
            }

            InputStream inputStream = img.getInputStream();
            User user = userService.showUserInfoByName(name);
            byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
            user.setHeadImg(bytes);
            Integer i = userService.setHeadImg(user);
            if (i>0){
                return "成功";
            }else{
                return "error"+"上传失败！";
            }

        }else{
            return "error"+"未上传图片!";
        }
    }

    @RequestMapping("/img")
    public void setHeadImg(String name, HttpServletResponse resp)  {
        User user = userService.showUserInfoByName(name);
        byte[] bytes = user.getHeadImg();
        OutputStream outputStream = null;
        try {
            outputStream=resp.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/toDynamic")
    public String toDynamic(HttpServletRequest req){
        User login = (User) req.getSession().getAttribute("user");
        if(login != null){
            String basePath = req.getScheme() + "://" +
                    req.getServerName() +
                    ":" + req.getServerPort() +
                    req.getContextPath() + "/";
            int pageNum;
            int pageSize;
            if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
                pageNum = 1;
            }else{
                pageNum = Integer.parseInt(req.getParameter("pageNum"));
            }
            if(req.getParameter("pageSize") == null){
                pageSize = Page.PAGE_SIZE;
            }else{
                pageSize = Integer.parseInt(req.getParameter("pageSize"));
            }
            Map map = new HashMap();
            map.put("userId", login.getId());
            map.put("pageNum", pageNum);
            map.put("pageSize", pageSize);
            Page<User> page = userService.getSubscribeUser(map);
            List<User> users = page.getItem();
            req.setAttribute("subscribeUser", users);
            return "dynamic";
        }else{
            return "login";
        }
    }

    @RequestMapping("/subscribe")
    @ResponseBody
    public int subscribe(int userId, int followUserId){
        userService.subscribeAddRelation(userId, followUserId, new Date());
        return userService.subscribe(followUserId);
    }

    @RequestMapping("/unsubscribe")
    @ResponseBody
    public int unsubscribe(int userId, int followUserId){
        userService.unsubscribeDeleteRelation(userId, followUserId);
        return userService.unsubscribe(followUserId);
    }

    @RequestMapping("/toDynamicWithBlog")
    public String toDynamicWithBlog(HttpServletRequest req, int userId){
        User login = (User) req.getSession().getAttribute("user");
        if(login != null){
            String basePath = req.getScheme() + "://" +
                    req.getServerName() +
                    ":" + req.getServerPort() +
                    req.getContextPath() + "/";
            int pageNum;
            int pageSize;
            if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
                pageNum = 1;
            }else{
                pageNum = Integer.parseInt(req.getParameter("pageNum"));
            }
            if(req.getParameter("pageSize") == null){
                pageSize = Page.PAGE_SIZE;
            }else{
                pageSize = Integer.parseInt(req.getParameter("pageSize"));
            }
            Map map1 = new HashMap();
            map1.put("userId", login.getId());
            map1.put("pageNum", pageNum);
            map1.put("pageSize", pageSize);
            Page<User> page = userService.getSubscribeUser(map1);
            List<User> users = page.getItem();
            req.setAttribute("subscribeUser", users);
            Map map2 = new HashMap();
            map2.put("userId", userId);
            map2.put("pageNum", pageNum);
            map2.put("pageSize", 4);
            Page<Blog> page1 = blogService.getBlogByUserIdOrderByTime(map2);
            page1.setUrl(basePath + "/user/toDynamicWithBlog?userId=" + userId);
            List<Blog> blogs = page1.getItem();
            Map<Blog, MyPair<String, User>> map3 = new LinkedHashMap<>();
            for(Blog blog : blogs){
                map3.put(blog, new MyPair<String, User>(new PrettyTime().format(blog.getBlogDate()), userService.showUserInfoByName(blog.getUserName())));
            }
            req.setAttribute("page", page1);
            req.setAttribute("subscribeBlogs", map3);
            return "dynamic";
        }else{
            return "login";
        }
    }

}
